package com.tanhua.admin.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.pojo.Analysis;
import com.tanhua.model.vo.AnalysisSummaryVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class AnalysisService {

    @Resource
    private LogMapper logMapper;

    @Resource
    private AnalysisMapper analysisMapper;


    /**
     * 定时统计日志数据到统计表中
     * 1、查询tb_log表中的数 （每日注册用户数，每日登陆用户，活跃的用户数据，次日留存的用户）
     * 2、构造Analysis对象
     * 3、完成统计数据的更新或者保存
     */

    //日期的格式
    private final String dateFormat = "yyyy-MM-dd";

    //统计当天用户的使用数据
    public void analysis() {
        //获取今天和昨天的日期
        String today = DateUtil.format(new Date(), dateFormat);
        String yesterday = DateUtil.yesterday().toString(dateFormat);

        DateTime todayDate = DateUtil.parse(today, dateFormat);

        Analysis analysis = new Analysis();
        //设置日期
        analysis.setRecordDate(todayDate);
        //设置新注册用户数
        analysis.setNumRegistered(logMapper.findCountByLogTimeAndType(today, "0102"));
        //设置活跃用户数
        analysis.setNumActive(logMapper.findCountByActive(today));
        //设置登录次数
        analysis.setNumLogin(logMapper.findCountByLogTimeAndType(today, "0101"));
        //设置次日留存用户数
        analysis.setNumRetention1d(logMapper.findNumRetention1d(today, yesterday));

        //查询今日的统计数据的对象
        Analysis todayAnalysis = analysisMapper.selectOne(Wrappers.lambdaQuery(Analysis.class).eq(Analysis::getRecordDate, todayDate));

        if (todayAnalysis == null) {
            //如果没有统计对象 就插入一个
            analysisMapper.insert(analysis);
        } else {
            //有就修改数据
            analysis.setId(todayAnalysis.getId());
            analysisMapper.updateById(analysis);
        }
    }

    //统计数据
    public AnalysisSummaryVo summary() {
        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        //获取昨日和今日统计数据对象
        String today = DateUtil.format(new Date(), dateFormat);
        String yesterday = DateUtil.yesterday().toString(dateFormat);

        DateTime todayDate = DateUtil.parse(today, dateFormat);
        DateTime yesterdayDate = DateUtil.parse(yesterday, dateFormat);

        //DateTime todayDate = DateUtil.parse("2020-09-14", dateFormat);
        //DateTime yesterdayDate = DateUtil.parse("2020-09-13", dateFormat);

        Analysis todayAnalysis = analysisMapper.selectOne(Wrappers.lambdaQuery(Analysis.class).eq(Analysis::getRecordDate, todayDate));
        Analysis yesterdayAnalysis = analysisMapper.selectOne(Wrappers.lambdaQuery(Analysis.class).eq(Analysis::getRecordDate, yesterdayDate));


        //设置累计用户数
        Long count = analysisMapper.cumulativeUsers();
        vo.setCumulativeUsers(count);
        //设置新增用户数量
        vo.setNewUsersToday(Long.valueOf(todayAnalysis.getNumRegistered()));
        //设置新增用户涨跌率
        vo.setNewUsersTodayRate(rate(todayAnalysis.getNumRegistered(),yesterdayAnalysis.getNumRegistered()));
        //设置今日登录次数
        vo.setLoginTimesToday(Long.valueOf(todayAnalysis.getNumLogin()));
        //设置今日登录次数涨跌率
        vo.setNewUsersTodayRate(rate(todayAnalysis.getNumLogin(),yesterdayAnalysis.getNumLogin()));
        //设置今日活跃用户数量
        vo.setActiveUsersToday(Long.valueOf(todayAnalysis.getNumActive()));
        //设置今日活跃用户涨跌率
        vo.setActiveUsersTodayRate(rate(todayAnalysis.getNumActive(),yesterdayAnalysis.getNumActive()));

        return vo;
    }

    //根据今日和昨日数据计算涨跌率
    private Integer rate(int today, int yesterday) {
        int result = 0;

        if (yesterday == 0) {
            //如果前一天的数据量为0 今天每多一个用户的操作 ,增长率就增加100
            result = today * 100;
        } else {
            result = (today - yesterday) * 100 / yesterday;
        }

        return result;
    }
}
